package com.eight.group.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.eight.group.constant.MessageConstant;
import com.eight.group.entity.PageResult;
import com.eight.group.entity.QueryPageBean;
import com.eight.group.entity.Result;
import com.eight.group.mapper.MemberMapper;
import com.eight.group.mapper.OrderMapper;
import com.eight.group.mapper.OrderSettingMapper;
import com.eight.group.mapper.SetmealMapper;
import com.eight.group.pojo.*;
import com.eight.group.utils.DateUtils;
import com.eight.group.vo.AddOrderVO;
import com.eight.group.vo.OrderAndMemberVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xqx.eight.group.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：xingquanxiang createTime：2019/11/12 15:31
 * description:
 */
@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 体检在线预约
     *
     * @param map 预约客户信息
     * @return Result
     */
    @Override
    public Result order(Map map) throws Exception {
        //获取预约日期
        String orderDate = (String) map.get("orderDate");
        //1.检查用户所选择的预约日期是否已经提前进行了预约设置，若果没有设置就无法进行预约
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(orderDate);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2.检查用户所选择的日期是否已经约满， 若果已经约满则无法进行预约
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            //已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3.检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");
        Member member = memberMapper.findByTelephone(telephone);
        if (member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();
            //转化表单预约日期
            Date date = new Date(DateUtils.parseString2Date(orderDate).getTime());
            String setmealId = (String) map.get("setmealId");
            //根据条件查询
            List<Order> orderList = orderMapper.findByCondition(new Order(memberId, date, Integer.parseInt(setmealId)));
            if (orderList != null && orderList.size() > 0) {
                //说明用户在重复预约，无法再次完成预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date(System.currentTimeMillis()));
            member.setFileNo(telephone);
            memberMapper.add(member);//自动完成会员注册
        }
        //预约成功，更新当日的与预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(new Date(DateUtils.parseString2Date(orderDate).getTime()));
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.parseInt((String)map.get("setmealId")));
        order.setSiteId((Integer) map.get("addressId"));
        try {
            //添加预约
            orderMapper.add(order);
            //设置已预约人数 +1
            orderSetting.setReservations(orderSetting.getReservations() + 1);
            orderSettingMapper.editReservationsByOrderDate(orderSetting);
        } catch (Exception e) {
            return new Result(false, MessageConstant.ORDER_FAIL);
        }
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /**
     * 根据id查询预约信息
     *
     * @param id
     * @return Order
     */
    @Override
    public Order findById(Integer id) {
        return orderMapper.findById4Detail(id);
    }


    /**
     * 根据条件分页查询
     *
     * @param queryPageBean 条件参数
     * @return PageResult
     */
    @Override
    public PageResult findPageByCondition(QueryPageBean queryPageBean) {
        //调用分页助手api 设置当前页 ， 每页大小
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //执行查询，获取查询结果列表
        List<OrderAndMemberVO> orderList = orderMapper.findPageByCondition(queryPageBean.getQueryString());
        return new PageResult(new PageInfo<>(orderList).getTotal(), orderList);
    }

    /**
     * 后台管理新增预约（电话预约）
     * orderVO = AddOrderVO(name=张三, birthday=1998-05-10, idCard=530125199805102213, sex=1, orderDate=2019-11-28, phoneNumber=13529361695, maritalStatus=未婚)
     * setmealId = 12
     * setmealId = 14
     *
     * @param orderVO
     * @param setmealIds
     * @return
     */
    @Override
    public Result add(AddOrderVO orderVO, Integer[] setmealIds) {
        //获取预约日期
        String orderDate = null;
        try {
            orderDate = DateUtils.parseDate2String(orderVO.getOrderDate());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //1.检查用户所选择的预约日期是否已经提前进行了预约设置，若果没有设置就无法进行预约
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(orderDate);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2.检查用户所选择的日期是否已经约满， 若果已经约满则无法进行预约
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            //已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3.检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = orderVO.getPhoneNumber();
        Member member = memberMapper.findByTelephone(telephone);
        //存储重复预约的订单套餐id
        ArrayList<Integer> existed = new ArrayList<>();
        if (member != null && setmealIds != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();
            for (int i = 0; i < setmealIds.length; i++) {
                //根据条件查询
                List<Order> orderList = orderMapper.findByCondition(new Order(memberId, orderVO.getOrderDate(), setmealIds[i]));
                if (orderList != null && orderList.size() > 0) {
                    //说明用户在重复预约，无法再次完成预约
                    existed.add(setmealIds[i]);
                    setmealIds[i] = -1;
                }
            }
        } else {
            //4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((orderVO.getName()));
            member.setPhoneNumber(telephone);
            member.setIdCard(orderVO.getIdCard());
            member.setSex(orderVO.getSex());
            member.setRegTime(new Date(System.currentTimeMillis()));
            memberMapper.add(member);//自动完成会员注册
        }
        //添加预约
        for (Integer setmealId : setmealIds) {
            if (!setmealId.equals("-1")){
                Order order = new Order();
                order.setMemberId(member.getId());
                order.setOrderDate(orderVO.getOrderDate());
                order.setOrderType(Order.ORDERTYPE_TELEPHONE);
                order.setOrderStatus(Order.ORDERSTATUS_NO);
                order.setSetmealId(setmealId);
                //添加预约
                orderMapper.add(order);
                //设置已预约人数 +1
                orderSetting.setReservations(orderSetting.getReservations() + 1);
                orderSettingMapper.editReservationsByOrderDate(orderSetting);
            }
        }
        if (existed!=null && existed.size()>0){
            StringBuilder sb = new StringBuilder(MessageConstant.ORDER_FAIL);
            sb.append("!");
            for (Integer setmealId : existed) {
                sb.append(setmealMapper.findById(setmealId).getName()).append("_");
            }
            sb.append(existed.size()).append("个套餐在预约时间已被当前用户预约");
            return new Result(false, sb.toString());
        }
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }

    /**
     * 根据id删除预约
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        orderMapper.deleteById(id);
    }

    /**
     * 根据id确认预约
     *
     * @param id
     */
    @Override
    public void confirm(Integer id) {
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("id", id);
        map.put("orderStatus", Order.ORDERSTATUS_YES);
        orderMapper.updateOrderStatusById(map);
    }

    /**
     * 编辑预约
     * TODO
     * @param orderVO
     * @param setmealIds
     * @return
     */
    @Override
    public Result edit(AddOrderVO orderVO, Integer[] setmealIds) {
        return null;
    }

    /**
     * 查询所有预约信息
     *
     * @return
     */
    @Override
    public List<OrderAndMemberVO> findAll() {
        return orderMapper.findAll();
    }
}
